import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Pagination,
  Empty,
  Spin,
  Row,
  Col,
  Image,
  Tabs
} from 'antd';
import { 
  SearchOutlined,
  ShopOutlined,
  LinkOutlined,
  FireOutlined
} from '@ant-design/icons';
import './Products.scss';

const { Search } = Input;
const { Option } = Select;

const Products: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [sortBy, setSortBy] = useState('latest');
  const [activeTab, setActiveTab] = useState('all');

  // 好价推荐数据
  const mockProducts = [
    {
      id: '1',
      title: 'AirPods Pro 2代',
      description: '苹果官方正品，主动降噪，音质清晰',
      price: 1299,
      discount: 32,
      image: 'https://picsum.photos/200/200?random=31',
      category: '电子产品',
      source: '京东自营',
      sourceUrl: 'https://jd.com',
      createdAt: '2024-01-15T10:00:00Z',
    },
    {
      id: '2',
      title: '小米13 Ultra',
      description: '徕卡影像，骁龙8 Gen2，专业摄影手机',
      price: 3999,
      discount: 33,
      image: 'https://picsum.photos/200/200?random=32',
      category: '电子产品',
      source: '小米商城',
      sourceUrl: 'https://mi.com',
      createdAt: '2024-01-15T09:30:00Z',
    },
    {
      id: '3',
      title: 'Nike Air Force 1',
      description: '经典小白鞋，百搭必备，舒适透气',
      price: 399,
      discount: 43,
      image: 'https://picsum.photos/200/200?random=33',
      category: '服装鞋帽',
      source: '天猫官方',
      sourceUrl: 'https://tmall.com',
      createdAt: '2024-01-15T08:45:00Z',
    },
    {
      id: '4',
      title: '星巴克咖啡豆',
      description: '哥伦比亚咖啡豆，香醇浓郁，适合手冲',
      price: 89,
      discount: 31,
      image: 'https://picsum.photos/200/200?random=34',
      category: '食品饮料',
      source: '星巴克官方',
      sourceUrl: 'https://starbucks.com',
      createdAt: '2024-01-14T16:30:00Z',
    },
    {
      id: '5',
      title: '无印良品收纳盒',
      description: '简约设计，多规格收纳，整理神器',
      price: 29,
      discount: 41,
      image: 'https://picsum.photos/200/200?random=35',
      category: '生活用品',
      source: '无印良品',
      sourceUrl: 'https://muji.com',
      createdAt: '2024-01-14T14:20:00Z',
    },
    {
      id: '6',
      title: 'MacBook Air M2',
      description: '苹果M2芯片，轻薄便携，性能强劲',
      price: 7999,
      discount: 20,
      image: 'https://picsum.photos/200/200?random=36',
      category: '电子产品',
      source: '苹果官网',
      sourceUrl: 'https://apple.com',
      createdAt: '2024-01-14T11:15:00Z',
    },
  ];

  const categories = [
    { key: 'all', label: '全部分类' },
    { key: 'electronics', label: '电子产品' },
    { key: 'clothing', label: '服装鞋帽' },
    { key: 'food', label: '食品饮料' },
    { key: 'daily', label: '生活用品' },
    { key: 'books', label: '图书文具' },
  ];

  useEffect(() => {
    loadProducts();
  }, [currentPage, searchKeyword, sortBy, activeTab]);

  const loadProducts = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filteredProducts = mockProducts;
      
      // 按分类过滤
      if (activeTab !== 'all') {
        filteredProducts = mockProducts.filter(product => {
          switch (activeTab) {
            case 'electronics':
              return product.category === '电子产品';
            case 'clothing':
              return product.category === '服装鞋帽';
            case 'food':
              return product.category === '食品饮料';
            case 'daily':
              return product.category === '生活用品';
            case 'books':
              return product.category === '图书文具';
            default:
              return true;
          }
        });
      }
      
      // 按关键词搜索
      if (searchKeyword) {
        filteredProducts = filteredProducts.filter(product => 
          product.title.includes(searchKeyword) || 
          product.category.includes(searchKeyword) ||
          product.source.includes(searchKeyword)
        );
      }
      
      // 排序
      filteredProducts.sort((a, b) => {
        switch (sortBy) {
          case 'latest':
            return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
          case 'price-low':
            return a.price - b.price;
          case 'price-high':
            return b.price - a.price;
          case 'discount':
            return b.discount - a.discount;
          default:
            return 0;
        }
      });
      
      setProducts(filteredProducts);
      setTotal(filteredProducts.length);
    } catch (error) {
      console.error('加载好价推荐失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleProductClick = (productId: string) => {
    navigate(`/products/${productId}`);
  };

  const handleVisitSource = (sourceUrl: string, e: React.MouseEvent) => {
    e.stopPropagation();
    window.open(sourceUrl, '_blank');
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleSortChange = (value: string) => {
    setSortBy(value);
    setCurrentPage(1);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };

  const getCategoryColor = (category: string) => {
    const colors = {
      '电子产品': 'blue',
      '服装鞋帽': 'green',
      '食品饮料': 'orange',
      '生活用品': 'purple',
      '图书文具': 'cyan',
    };
    return colors[category as keyof typeof colors] || 'default';
  };

  return (
    <div className="products-page">
      <div className="page-header">
        <div className="header-left">
          <h1>好价推荐</h1>
          <p>发现好价，分享实惠，省钱购物</p>
        </div>
      </div>

      {/* 分类标签 */}
      <Card className="category-card">
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          items={categories.map(cat => ({
            key: cat.key,
            label: cat.label,
          }))}
        />
      </Card>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索好价商品..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={sortBy}
              onChange={handleSortChange}
              style={{ width: 140 }}
            >
              <Option value="latest">最新推荐</Option>
              <Option value="price-low">价格从低到高</Option>
              <Option value="price-high">价格从高到低</Option>
              <Option value="discount">折扣最大</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 商品列表 */}
      <Card className="products-card">
        <Spin spinning={loading}>
          {products.length > 0 ? (
            <Row gutter={[16, 16]}>
              {products.map((product) => (
                <Col xs={24} sm={12} lg={8} xl={6} key={product.id}>
                  <Card
                    className="product-card"
                    hoverable
                    onClick={() => handleProductClick(product.id)}
                    cover={
                      <div className="product-image">
                        <Image
                          src={product.image}
                          alt={product.title}
                          height={200}
                          style={{ objectFit: 'cover' }}
                          preview={false}
                        />
                        <div className="discount-badge">
                          <FireOutlined />
                          <span>{product.discount}% OFF</span>
                        </div>
                        <Tag 
                          className="category-badge" 
                          color={getCategoryColor(product.category)}
                        >
                          {product.category}
                        </Tag>
                      </div>
                    }
                  >
                    <div className="product-info">
                      <div className="title-price-row">
                        <h3 className="product-title">{product.title}</h3>
                        <span className="price">¥{product.price}</span>
                      </div>
                      
                      <p className="product-description">{product.description}</p>
                      
                      <div className="product-footer">
                        <div className="source-info">
                          <ShopOutlined />
                          <span>{product.source}</span>
                        </div>
                        <Button 
                          type="primary" 
                          size="small"
                          icon={<LinkOutlined />}
                          onClick={(e) => handleVisitSource(product.sourceUrl, e)}
                        >
                          去购买
                        </Button>
                      </div>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          ) : (
            <Empty 
              description="暂无好价推荐"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
        
        {total > 0 && (
          <div className="pagination-wrapper">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={12}
              onChange={setCurrentPage}
              showSizeChanger={false}
              showQuickJumper
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </Card>
    </div>
  );
};

export default Products;